package week06

import "math"

// 152. 乘积最大子数组
// https://leetcode-cn.com/problems/maximum-product-subarray/

func maxProduct(nums []int) int {
	var maxdp = make([]int, 2)
	var mindp = make([]int, 2)
	maxdp[0] = math.MinInt32
	mindp[0] = math.MaxInt32
	var ans = maxdp[0]
	for i := 1; i <= len(nums); i++ {
		if nums[i-1] > 0 {
			maxdp[i&1] = max(maxdp[(i-1)&1] * nums[i-1], nums[i-1])
			mindp[i&1] = min(mindp[(i-1)&1] * nums[i-1], nums[i-1])
		} else {
			maxdp[i&1] = max(mindp[(i-1)&1] * nums[i-1], nums[i-1])
			mindp[i&1] = min(maxdp[(i-1)&1] * nums[i-1], nums[i-1])
		}
		ans = max(ans, maxdp[i&1])
	}
	return ans
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func min(x, y int) int {
	if x > y {
		return y
	}
	return x
}